package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
@Api(tags = "套餐相关接口")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache", allEntries = true)  // allEntries 删除所有缓存数据
    @ApiOperation(value = "新增套餐接口")
    public R<String> save(@RequestBody SetmealDto setmealDto) {

        log.info("套餐信息：{}", setmealDto);

        setmealService.saveWithDish(setmealDto);
/*
        // 可以选择清除所有缓存
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

        // 清除对应分类套餐的缓存数据
        String key = "dish_" + setmealDto.getCategoryId() + "_" + setmealDto.getStatus();
        redisTemplate.delete(key);
*/

        return R.success("新增套餐成功");
    }

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "套餐分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页记录数", required = true),
            @ApiImplicitParam(name = "name", value = "套餐名称", required = false)
    })
    public R<Page<SetmealDto>> page(int page, int pageSize, String name) {

        log.info("页码：{}, 数目：{}, 查询条件：{}", page, pageSize, name);

        // 构造分页构造器
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> setmealDtoPage = new Page<>(page, pageSize);

        // 构造条件
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        // 添加查询条件
        queryWrapper.like(name != null, Setmeal::getName, name);
        // 添加排序条件，根据更新时间降序排列
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);
        // 开始查询
        setmealService.page(pageInfo, queryWrapper);

        // 进行对象拷贝   除了 records 属性
        BeanUtils.copyProperties(pageInfo, setmealDtoPage, "records");
        // 获取查询到的对象
        List<Setmeal> setmeals = pageInfo.getRecords();
        List<SetmealDto> list = setmeals.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            // 对象拷贝
            BeanUtils.copyProperties(item, setmealDto);
            // 查询分类对象 id
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {   // 如若查询到category则将对应的类名添加到setmealDto中
                setmealDto.setCategoryName(category.getName());
            }

            return setmealDto;
        }).collect(Collectors.toList());

        setmealDtoPage.setRecords(list);    // 将结果插入分页构造器中

        return R.success(setmealDtoPage);
    }

    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache", allEntries = true)  // allEntries 删除所有缓存数据
    public R<String> deleteWithDish(@RequestParam List<Long> ids) {

        log.info("ids: {}", ids);

        setmealService.removeWithDish(ids);

        return R.success("套餐数据删除成功");
    }

    /**
     * 对套餐状态进行修改    批量/单个
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable int status, @RequestParam List<Long> ids) {

        log.info("status:{}, ids:{}", status, ids);

        // 构造条件
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Setmeal::getId, ids);
        // 获取对象
        List<Setmeal> list = setmealService.list(queryWrapper);
        // 对 状态status 进行修改
        list = list.stream().peek((item) ->
                item.setStatus(status)
        ).collect(Collectors.toList());
        // 重新更新 setmeal 表的数据
        setmealService.updateBatchById(list);

        // 清除套餐缓存数据
        for (Setmeal setmeal : list) {
            String key = "setmeal_" + setmeal.getCategoryId() + "_" + setmeal.getStatus();
            redisTemplate.delete(key);
        }

        return R.success("更新套餐状态成功");
    }

    /**
     * 用户端 查询套餐菜品数据
     * @param setmeal
     * @return
     */
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")
    @GetMapping("/list")
    public R<List<SetmealDto>> list(Setmeal setmeal) {

        List<SetmealDto> setmealDtoList = null;
/*
        // 创建储存到缓存数据对应的 key
        String key = "setmeal_" + setmeal.getCategoryId() + "_" + setmeal.getStatus();

        // 查询Redis缓存中是否存在套餐数据
        setmealDtoList = (List<SetmealDto>) redisTemplate.opsForValue().get(key);

        if (setmealDtoList != null) {
            // 如果缓存中存在套餐数据  则直接返回
            return R.success(setmealDtoList);
        }
*/
        log.info("setmeal: {}", setmeal);

        // 条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        // 等值条件
        queryWrapper.eq(Setmeal::getCategoryId, setmeal.getCategoryId());
        queryWrapper.eq(Setmeal::getStatus, setmeal.getStatus());
        // 增加排序条件
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        // 开始查询
        List<Setmeal> list = setmealService.list(queryWrapper);

        setmealDtoList = list.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();

            // 复制对象
            BeanUtils.copyProperties(item, setmealDto);

            // 查询套餐对应的菜品信息
            LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper = new LambdaQueryWrapper<>();
            setmealDishLambdaQueryWrapper.eq(SetmealDish::getDishId, item.getId());
            List<SetmealDish> setmealDishList = setmealDishService.list(setmealDishLambdaQueryWrapper);

            setmealDto.setSetmealDishes(setmealDishList);

            return setmealDto;
        }).collect(Collectors.toList());

/*
        // 如果缓存中不存在套餐数据 则进行数据库查询数据  并将查询到的数据保存到缓存中
        redisTemplate.opsForValue().set(key, setmealDtoList, 60, TimeUnit.MINUTES);
*/

        return R.success(setmealDtoList);
    }

    /**
     * 根据 id 查询套餐数据
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public R<List<SetmealDish>> dishList(@PathVariable Long id) {

        log.info("id: {}", id);

        // 条件构造器
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, id);

        List<SetmealDish> list = setmealDishService.list(queryWrapper);

        return R.success(list);
    }

}
